package com.software.chemistry.service.Impl;

import com.software.chemistry.entity.ModelInfo;
import com.software.chemistry.repository.ModelInfoRepository;
import com.software.chemistry.service.ModelInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class ModelInfoServiceImpl implements ModelInfoService {
    @Autowired
    private ModelInfoRepository modelInfoRepository;

    @Override
    public List<ModelInfo> findCommonModelInfo(Pageable pageable) {
        //查询条件为model_id为 1-15
        Specification<ModelInfo> specification = new Specification<ModelInfo>() {
            @Override
            public Predicate toPredicate(Root<ModelInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                predicates.add(criteriaBuilder.between(root.get("modelId"), "001", "015"));
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Page<ModelInfo> page = modelInfoRepository.findAll(specification, pageable);
        List<ModelInfo> modelInfos = page.getContent();
        return modelInfos;
    }

    @Override
    public List<ModelInfo> findModelInfoByTypeId(String typeId) {

        List<ModelInfo> modelInfos = modelInfoRepository.findModelInfoByTypeId(typeId);
        return modelInfos;
    }

    @Override
    public List<ModelInfo> findByModelNameOrModelDescription(String obtain) {

        List<ModelInfo> modelInfos = modelInfoRepository.findByModelNameOrModelDescription(obtain);
        return modelInfos;
    }

}
